<template>
    <div  style="width: 100%;height: 100vh;background-color: darkslateblue;overflow:hidden">
      <div style="width: 400px;margin: 150px auto">
          <div style="color: #cccccc;font-size: 30px;text-align: center;padding: 30px 0">欢迎登录</div>
        <el-form ref="form" :model="form" label-width="80px" size="normal">
          <el-form-item prop="username">
            <el-input prefix-icon="el-icon-user" v-model="form.username" >
                <template #prefix>
                    <User />
                </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock"  v-model="form.password" type="password"  ref="pwdInput">
              <template #prefix>
                <Lock />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item >
            <el-button style="width: 100%" type="primary" @click="login">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
</template>

<script>
import {User, Lock,Menu as IconMenu} from '@element-plus/icons-vue'
import request from "@/utils/request";
export default {
  name: "LoginView",
  components:{Lock,User,IconMenu},
  data(){
    return{
      form:{},
      rules:{
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ]
      },
      state:0,
    }
  },
  mounted() {
    window.addEventListener('keyup', this.handleKeyDown);
  },
  methods:{
    login(){
         if(this.$refs['form']!=null){
           this.$refs['form'].validate(valid=>{
             if(valid){
               //满足验证规则之后，发送请求
               request.post("/user/login",this.form).then(res=>{
                 if(res.code==0){
                   this.$message.success("登录成功");
                   delete this.form.password
                   sessionStorage.setItem("user",JSON.stringify(this.form))
                   this.$root.user = this.form;
                   this.$router.push("/");
                 }else{
                   this.$message.error(res.msg);
                 }
               })
             }
           })
         }
    },
    handleKeyDown(event) {
      if (event.key === 'Enter') {
        // 处理回车键按下事件
        this.enterEvent();
      }
    },
    enterEvent() {
       if(this.form.password){
          this.login();
       }else{
         //切换光标到
         this.$refs['pwdInput'].focus();
       }
    }
  },
  destroyed() {
    window.removeEventListener('keyup', this.handleKeyDown);
  },
}
</script>

<style scoped>

</style>